'use strict';

let workspace = null;
let textCode = null;

document.addEventListener("DOMContentLoaded", function () {
	// 将Blockly工作区插入div
	workspace = Blockly.inject('blocklyDiv',
		{
			toolbox: document.getElementById('toolbox-categories'),
			media: "media/"
		});

	// 定义部分Utility
	function block2Code(language) {
		return Blockly[language].workspaceToCode(workspace);
	}

	function saveBlock() {
		// 使用var将变量声明于整个函数作用域
		// 否则catch中无法使用
		try {
			var xml = Blockly.Xml.workspaceToDom(workspace);
			var xml_text = Blockly.Xml.domToText(xml);
			channel.objects.Messenger.receiveXML(xml_text);
		} catch (e) {
			alert("debug mode, see xml in console");
			console.log(xml_text);
		}
	}

	// 弹出对话框，接受用户输入XML
	function loadBlock() {
		try {
			let xml_text = prompt("Please enter XML code", "");
			if (!xml_text)
				return;

			let xml = Blockly.Xml.textToDom(xml_text);
			workspace.clear();
			Blockly.Xml.domToWorkspace(xml, workspace);
		} catch (e) {
			alert(e);
		}
	}

	// 用于接受Qt传来的文件内容
	function loadXML(xml_text) {
		try {
			if (!xml_text)
				return;

			let xml = Blockly.Xml.textToDom(xml_text);
			workspace.clear();
			Blockly.Xml.domToWorkspace(xml, workspace);
		} catch (e) {
			alert(e);
		}
	}

	function clearTrashCan() {
		workspace.trashcan.emptyContents();
	}

	// 为方便测试，定义几个hidden button
	const lang = 'Lox';
	const buttonConvert = document.getElementById('blocklyConvert');
	buttonConvert.addEventListener('click', function () {
		alert("Check the console for the generated output.");
		textCode = block2Code(lang);
		console.log(textCode);
	})

	const buttonSave = document.getElementById('blocklySerialize');
	buttonSave.addEventListener('click', saveBlock)

	const buttonLoad = document.getElementById('blocklyDeserialize');
	buttonLoad.addEventListener('click', loadBlock)

	const buttonClearTrash = document.getElementById('blocklyClearTrash');
	buttonClearTrash.addEventListener('click', clearTrashCan)

	// 初始化QWebChannel（全局）
	// delete try block when move to Qt
	try {
		window.channel = new QWebChannel(qt.webChannelTransport,
			function (channel) {
				// you could connect signal and slot here
				let messenger = channel.objects.Messenger;
				messenger.triggerSave.connect(saveBlock);
				messenger.triggerLoadInput.connect(loadBlock);
				messenger.triggerLoadFile.connect(loadXML);
				messenger.clearTrash.connect(clearTrashCan);
			});
	}
	catch (e) { }

	workspace.addChangeListener((event) => {
		if (event.type == Blockly.Events.BLOCK_MOVE || event.type == Blockly.Events.BLOCK_CHANGE) {
			let currentCode = block2Code(lang);
			if (currentCode != textCode) {
				textCode = currentCode;
				// send code to Qt
				channel.objects.Messenger.receiveCode(textCode);
			}
		}
	});
});